const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

// 导入子路由
const habitsRoutes = require('./admin/habits');

// 验证JWT中间件，并检查用户权限
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ error: '未授权访问' });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.userId = decoded.userId;
    
    // 获取用户角色
    const userResult = global.db.exec(`
      SELECT role FROM users WHERE id = ${req.userId}
    `);
    
    if (userResult.length === 0 || userResult[0].values.length === 0) {
      return res.status(404).json({ error: '用户不存在' });
    }
    
    req.userRole = userResult[0].values[0][0];
    next();
  } catch (error) {
    return res.status(403).json({ error: '无效的令牌' });
  }
};

// 管理员权限检查中间件
const checkAdminAccess = async (req, res, next) => {
  try {
    // 检查角色是否有管理员权限
    let hasAccess = false;
    
    if (req.userRole === 'admin') {
      hasAccess = true;
    } else if (req.userRole === 'editor') {
      // 编辑角色只有部分权限
      const requestedPath = req.path;
      if (requestedPath.includes('/articles') || requestedPath.includes('/habits')) {
        hasAccess = true;
      }
    }
    
    if (!hasAccess) {
      return res.status(403).json({ error: '无权访问管理功能' });
    }
    
    next();
  } catch (error) {
    console.error('检查管理员权限错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
};

// 检查用户是否有管理员访问权限
router.get('/check-access', authenticateToken, (req, res) => {
  try {
    // 查询用户角色
    const userResult = global.db.exec(`
      SELECT id, role, email FROM users WHERE id = ${req.userId}
    `);
    
    if (userResult.length === 0 || userResult[0].values.length === 0) {
      return res.json({ hasAccess: false });
    }
    
    const userRole = userResult[0].values[0][1];
    const userEmail = userResult[0].values[0][2];
    
    // 管理员和编辑都有权限访问后台
    const hasAccess = userRole === 'admin' || userRole === 'editor';
    
    res.json({ hasAccess, role: userRole, email: userEmail });
  } catch (error) {
    console.error('检查管理员权限错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 获取仪表盘数据
router.get('/dashboard', authenticateToken, checkAdminAccess, (req, res) => {
  try {
    // 获取用户总数
    const totalUsersStmt = global.db.prepare('SELECT COUNT(*) as count FROM users');
    const { count: totalUsers } = totalUsersStmt.get();
    
    // 获取习惯总数
    const totalHabitsStmt = global.db.prepare('SELECT COUNT(*) as count FROM habits');
    const { count: totalHabits } = totalHabitsStmt.get();
    
    // 获取已完成的习惯次数
    const completedHabitsStmt = global.db.prepare('SELECT COUNT(*) as count FROM habit_completions');
    const { count: completedHabits } = completedHabitsStmt.get();
    
    // 获取文章总数
    const totalArticlesStmt = global.db.prepare('SELECT COUNT(*) as count FROM articles');
    const { count: totalArticles } = totalArticlesStmt.get();
    
    // 获取最近注册的用户
    const recentUsersQuery = `
      SELECT id, email, created_at
      FROM users
      ORDER BY created_at DESC
      LIMIT 5
    `;
    const recentUsersResult = global.db.exec(recentUsersQuery);
    const recentUsers = [];
    
    if (recentUsersResult.length > 0) {
      const { columns, values } = recentUsersResult[0];
      for (const row of values) {
        const user = {};
        columns.forEach((col, i) => {
          user[col] = row[i];
        });
        recentUsers.push(user);
      }
    }
    
    // 获取最近创建的习惯
    const recentHabitsQuery = `
      SELECT id, title, created_at
      FROM habits
      ORDER BY created_at DESC
      LIMIT 5
    `;
    const recentHabitsResult = global.db.exec(recentHabitsQuery);
    const recentHabits = [];
    
    if (recentHabitsResult.length > 0) {
      const { columns, values } = recentHabitsResult[0];
      for (const row of values) {
        const habit = {};
        columns.forEach((col, i) => {
          habit[col] = row[i];
        });
        recentHabits.push(habit);
      }
    }
    
    res.json({
      totalUsers,
      totalHabits,
      completedHabits,
      totalArticles,
      recentUsers,
      recentHabits
    });
  } catch (error) {
    console.error('获取仪表盘数据错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 文章管理接口
router.get('/articles', authenticateToken, checkAdminAccess, (req, res) => {
  try {
    const page = req.query.page ? parseInt(req.query.page) : 1;
    const limit = req.query.limit ? parseInt(req.query.limit) : 10;
    const offset = (page - 1) * limit;
    
    // 获取文章列表
    const articles = [];
    const results = global.db.exec(`
      SELECT id, title, substr(content, 1, 100) as summary, created_at, updated_at, is_pinned, status
      FROM articles
      ORDER BY updated_at DESC
      LIMIT ${limit} OFFSET ${offset}
    `);
    
    if (results.length > 0) {
      const { columns, values } = results[0];
      for (const row of values) {
        const article = {};
        columns.forEach((col, i) => {
          article[col] = row[i];
        });
        articles.push(article);
      }
    }
    
    // 获取文章总数
    const countResult = global.db.exec(`
      SELECT COUNT(*) FROM articles
    `);
    
    const totalCount = countResult[0].values[0][0];
    
    res.json({
      articles,
      pagination: {
        total: totalCount,
        page,
        limit,
        totalPages: Math.ceil(totalCount / limit)
      }
    });
  } catch (error) {
    console.error('获取管理文章列表错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 更新文章状态（置顶/取消置顶，发布/草稿）
router.patch('/articles/:id', authenticateToken, checkAdminAccess, (req, res) => {
  try {
    const { id } = req.params;
    const { status, is_pinned } = req.body;
    
    // 检查文章是否存在
    const articleCheck = global.db.exec(`SELECT id FROM articles WHERE id = ${id}`);
    if (articleCheck.length === 0 || articleCheck[0].values.length === 0) {
      return res.status(404).json({ error: '文章不存在' });
    }
    
    // 构建更新语句
    let updateQuery = 'UPDATE articles SET ';
    let updateValues = [];
    
    if (status !== undefined) {
      if (status !== 'draft' && status !== 'published') {
        return res.status(400).json({ error: '状态只能是 draft 或 published' });
      }
      updateQuery += 'status = ?, ';
      updateValues.push(status);
    }
    
    if (is_pinned !== undefined) {
      if (typeof is_pinned !== 'boolean' && is_pinned !== 0 && is_pinned !== 1) {
        return res.status(400).json({ error: '置顶状态必须是布尔值' });
      }
      updateQuery += 'is_pinned = ?, ';
      updateValues.push(is_pinned ? 1 : 0);
    }
    
    // 更新时间
    updateQuery += 'updated_at = ? ';
    updateValues.push(new Date().toISOString());
    
    // 完成更新语句
    updateQuery += 'WHERE id = ?';
    updateValues.push(id);
    
    // 执行更新
    const updateStmt = global.db.prepare(updateQuery);
    updateStmt.run(updateValues);
    
    // 保存数据库
    global.saveDatabase();
    
    res.json({ 
      success: true, 
      message: '文章状态已更新',
      article_id: id
    });
  } catch (error) {
    console.error('更新文章状态错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 删除文章
router.delete('/articles/:id', authenticateToken, checkAdminAccess, (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查文章是否存在
    const articleCheck = global.db.exec(`SELECT id FROM articles WHERE id = ${id}`);
    if (articleCheck.length === 0 || articleCheck[0].values.length === 0) {
      return res.status(404).json({ error: '文章不存在' });
    }
    
    // 执行删除
    const deleteStmt = global.db.prepare('DELETE FROM articles WHERE id = ?');
    deleteStmt.run([id]);
    
    // 保存数据库
    global.saveDatabase();
    
    res.json({
      success: true,
      message: '文章已删除',
      article_id: id
    });
  } catch (error) {
    console.error('删除文章错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 创建新文章
router.post('/articles', authenticateToken, checkAdminAccess, (req, res) => {
  try {
    const { title, content, is_pinned = 0, is_published = false } = req.body;
    
    if (!title || !content) {
      return res.status(400).json({ error: '标题和内容是必填项' });
    }
    
    const now = new Date().toISOString();
    
    // 根据is_published参数设置status值
    const status = is_published ? 'published' : 'draft';
    
    // 创建文章
    const stmt = global.db.prepare(`
      INSERT INTO articles (title, content, author_id, created_at, updated_at, is_pinned, status)
      VALUES (?, ?, ?, ?, ?, ?, ?)
    `);
    
    stmt.run([
      title,
      content,
      req.userId,
      now,
      now,
      is_pinned ? 1 : 0,
      status
    ]);
    
    // 获取新文章ID
    const idResult = global.db.exec('SELECT last_insert_rowid() as id')[0];
    const articleId = idResult.values[0][0];
    
    // 保存数据库
    global.saveDatabase();
    
    res.json({ 
      id: articleId,
      title,
      content,
      created_at: now,
      updated_at: now,
      is_pinned: is_pinned ? 1 : 0,
      status,
      is_published: is_published
    });
  } catch (error) {
    console.error('创建文章错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 更新文章内容
router.put('/articles/:id', authenticateToken, checkAdminAccess, (req, res) => {
  try {
    const { id } = req.params;
    const { title, content, is_pinned, is_published } = req.body;
    
    if (!title || !content) {
      return res.status(400).json({ error: '标题和内容是必填项' });
    }
    
    // 检查文章是否存在
    const articleResult = global.db.exec(`
      SELECT id FROM articles WHERE id = ${id}
    `);
    
    if (articleResult.length === 0 || articleResult[0].values.length === 0) {
      return res.status(404).json({ error: '文章不存在' });
    }
    
    const now = new Date().toISOString();
    
    // 根据is_published参数设置status值
    const status = is_published ? 'published' : 'draft';
    
    // 更新文章
    const stmt = global.db.prepare(`
      UPDATE articles
      SET title = ?, content = ?, updated_at = ?, is_pinned = ?, status = ?
      WHERE id = ?
    `);
    
    stmt.run([
      title,
      content,
      now,
      is_pinned ? 1 : 0,
      status,
      id
    ]);
    
    // 保存数据库
    global.saveDatabase();
    
    res.json({ 
      id: parseInt(id),
      title,
      content,
      updated_at: now,
      is_pinned: is_pinned ? 1 : 0,
      status,
      is_published: is_published ? 1 : 0
    });
  } catch (error) {
    console.error('更新文章错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 用户管理接口
router.get('/users', authenticateToken, checkAdminAccess, (req, res) => {
  try {
    // 检查是否为管理员
    if (req.userRole !== 'admin') {
      return res.status(403).json({ error: '仅管理员可以管理用户' });
    }
    
    const page = req.query.page ? parseInt(req.query.page) : 1;
    const limit = req.query.limit ? parseInt(req.query.limit) : 10;
    const offset = (page - 1) * limit;
    
    // 获取用户列表
    const users = [];
    const results = global.db.exec(`
      SELECT id, email, role, created_at, motivation_score
      FROM users
      ORDER BY id DESC
      LIMIT ${limit} OFFSET ${offset}
    `);
    
    if (results.length > 0) {
      const { columns, values } = results[0];
      for (const row of values) {
        const user = {};
        columns.forEach((col, i) => {
          user[col] = row[i];
        });
        users.push(user);
      }
    }
    
    // 获取用户总数
    const countResult = global.db.exec(`
      SELECT COUNT(*) FROM users
    `);
    
    const totalCount = countResult[0].values[0][0];
    
    res.json({
      users,
      pagination: {
        total: totalCount,
        page,
        limit,
        totalPages: Math.ceil(totalCount / limit)
      }
    });
  } catch (error) {
    console.error('获取用户列表错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 更新用户角色
router.patch('/users/:id/role', authenticateToken, checkAdminAccess, (req, res) => {
  try {
    // 检查是否为管理员
    if (req.userRole !== 'admin') {
      return res.status(403).json({ error: '仅管理员可以管理用户角色' });
    }
    
    const { id } = req.params;
    const { role } = req.body;
    
    if (!role || !['admin', 'editor', 'user'].includes(role)) {
      return res.status(400).json({ error: '无效的角色值' });
    }
    
    // 检查用户是否存在
    const userResult = global.db.exec(`
      SELECT id FROM users WHERE id = ${id}
    `);
    
    if (userResult.length === 0 || userResult[0].values.length === 0) {
      return res.status(404).json({ error: '用户不存在' });
    }
    
    // 防止删除最后一个管理员
    if (id == req.userId && role !== 'admin') {
      const adminCountResult = global.db.exec(`
        SELECT COUNT(*) FROM users WHERE role = 'admin'
      `);
      
      if (adminCountResult[0].values[0][0] <= 1) {
        return res.status(400).json({ error: '不能更改最后一个管理员的角色' });
      }
    }
    
    // 更新用户角色
    global.db.exec(`
      UPDATE users
      SET role = '${role}'
      WHERE id = ${id}
    `);
    
    // 保存数据库
    global.saveDatabase();
    
    res.json({ success: true });
  } catch (error) {
    console.error('更新用户角色错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 系统设置接口
router.get('/settings', authenticateToken, checkAdminAccess, (req, res) => {
  try {
    // 获取所有设置
    const settings = {};
    const results = global.db.exec(`
      SELECT key, value, description
      FROM settings
    `);
    
    if (results.length > 0) {
      const { columns, values } = results[0];
      for (const row of values) {
        const setting = {};
        columns.forEach((col, i) => {
          setting[col] = row[i];
        });
        settings[setting.key] = setting;
      }
    }
    
    res.json(settings);
  } catch (error) {
    console.error('获取系统设置错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 更新系统设置
router.put('/settings', authenticateToken, checkAdminAccess, (req, res) => {
  try {
    const { settings } = req.body;
    
    if (!settings || typeof settings !== 'object') {
      return res.status(400).json({ error: '无效的设置数据' });
    }
    
    // 更新每个设置项
    const updatePromises = Object.entries(settings).map(([key, value]) => {
      return new Promise((resolve, reject) => {
        try {
          const stmt = global.db.prepare(`
            UPDATE settings
            SET value = ?
            WHERE key = ?
          `);
          
          stmt.run([value, key]);
          resolve();
        } catch (error) {
          reject(error);
        }
      });
    });
    
    Promise.all(updatePromises)
      .then(() => {
        // 保存数据库
        global.saveDatabase();
        
        res.json({ success: true });
      })
      .catch(error => {
        console.error('更新设置错误:', error);
        res.status(500).json({ error: '更新设置失败' });
      });
  } catch (error) {
    console.error('更新系统设置错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 添加习惯管理路由
router.use('/habits', authenticateToken, checkAdminAccess, habitsRoutes);

// 导出路由
module.exports = router;

// 导出authenticateToken中间件
module.exports.authenticateToken = authenticateToken;